import React from 'react'
import SearchHeader from '../../components/SearchHeader'

import { Flex, Toast } from 'antd-mobile'
import { List, AutoSizer, WindowScroller, InfiniteLoader } from 'react-virtualized'

import Filter from './components/Filter'

import styles from './index.module.css'

// 导入自定义的axios
import { API } from '../../utils/api'

import HouseItem from '../../components/HouseItem'

// 导入基础路径
import { BASE_URL } from '../../utils/url'

// 导入吸顶组件
import Sticky from '../../components/Sticky'

import NoHouse from '../../components/NoHouse'

// 获取当前城市定位信息
let curCity = JSON.parse(localStorage.getItem('hkzf_city'))

export default class HouseList extends React.Component {
  state = {
    list: [], //列表数据
    count: 0, //总条数
    isLoading: false //数据是否加载中
  }

  // 初始化实例属性
  filters = {}

  componentDidMount() {
    curCity = JSON.parse(localStorage.getItem('hkzf_city'))
    this.searchHouseList()
  }
  // 用来获取房屋列表数据
  async searchHouseList() {
    // 开启loading
    Toast.loading('加载中...', 0, null, false)
    this.setState({
      isLoading: true
    })
    // 获取当前城市ID值
    const { value } = JSON.parse(localStorage.getItem('hkzf_city'))
    const res = await API.get('/houses', {
      params: {
        cityId: value,
        ...this.filters,
        start: 1,
        end: 500
      }
    })
    const { list, count } = res.data.body

    // 关闭loading
    Toast.hide()

    // 提示房源数量
    if (count !== 0) {
      Toast.info(`共找到${count} 套房源`, 2, null, false)
    }

    this.setState({
      list,
      count,
      isLoading: false
    })
  }

  // 接受Filter组件中的筛选条件数据
  onFilters = (filters) => {
    // 返回页面顶部
    window.scrollTo(0, 0)
    this.filters = filters
    this.filters.rentType = this.filters.mode
    // 调用方法获取房屋数据
    this.searchHouseList()
  }

  renderHouseList = ({
    key,
    index,
    style,
  }) => {
    // 根据索引号获取当前行的房屋数据
    const { list } = this.state
    const house = list[index]

    // 判断house是否存在
    // 不存在渲染 loading 图片
    if (!house) {
      return (<div key={key} style={style}>
        <p className={styles.loading}></p>
      </div>)
    }

    return (
      <HouseItem key={key} style={style} src={BASE_URL + house.houseImg} title={house.title} desc={house.desc} tags={house.tags} price={house.price} onClick={() => this.props.history.push(`/detail/${house.houseCode}`)}></HouseItem>
    )
  }


  // 判断列表中的每一行是否加载完成
  isRowLoaded = ({ index }) => {
    return !!this.state.list[index]
  }

  // 用来获取更多房屋列表数据
  loadMoreRows = ({ startIndex, stopIndex }) => {
    const { value } = JSON.parse(localStorage.getItem('hkzf_city'))
    return new Promise(resolve => {
      // 
      API.get('/houses', {
        params: {
          cityId: value,
          ...this.filters,
          start: startIndex,
          end: stopIndex
        }
      }).then(res => {
        this.setState({
          list: [...this.state.list, ...res.data.body.list]
        })

        // 数据加载完成时，调用resolve
        resolve()
      })
    })
  }

  renderList() {
    const { count, isLoading } = this.state

    // 关键在数据加载完成后再进行判断
    if (count === 0 && isLoading === false) {
      return <NoHouse>没有找到房源,请您换个搜索条件吧！</NoHouse>
    }
    return (
      <WindowScroller>
        {({ height, isScrolling, scrollTop }) => (
          <AutoSizer>
            {({ width }) => (
              <List
                // onRowsRendered={onRowsRendered}
                // ref={registerChild}
                autoHeight  //设置真正的高度
                width={width} //视口的宽度
                height={height} //视口的高度
                rowCount={count}  //List列表项的行数
                rowHeight={120}  //设定每一行的高度
                rowRenderer={this.renderHouseList} //渲染列表项的每一行
                isScrolling={isScrolling}
                scrollTop={scrollTop}
              />
            )}
          </AutoSizer>
        )}
      </WindowScroller>
    )
  }

  render() {
    const { count } = this.state
    return (
      <div>
        <Flex className={styles.header}>
          <i className="iconfont icon-back"></i>
          <SearchHeader cityName={curCity.label} className={styles.searchHeader} />
        </Flex>

        {/* 条件筛选 */}
        <Sticky height={40}>
          <Filter onFilters={this.onFilters} />
        </Sticky>

        {/* 房屋列表 */}
        {/* <div className={styles.houseItems}>
          <InfiniteLoader
            isRowLoader={this.isRowLoaded}
            loadMoreRows={this.loadMoreRows}
            rowCount={count}
          >
            {({ onRowsRendered, registerChild }) => {
              <WindowScroller>
                {({ height, isScrolling, scrollTop }) => (
                  <AutoSizer>
                    {({ width }) => (
                      <List
                        onRowsRendered={onRowsRendered}
                        ref={registerChild}
                        autoHeight  //设置真正的高度
                        width={width} //视口的宽度
                        height={height} //视口的高度
                        rowCount={count}  //List列表项的行数
                        rowHeight={120}  //设定每一行的高度
                        rowRenderer={this.renderHouseList} //渲染列表项的每一行
                        isScrolling={isScrolling}
                        scrollTop={scrollTop}
                      />
                    )}
                  </AutoSizer>
                )}
              </WindowScroller>
            }}
          </InfiniteLoader> */}

        <div>{this.renderList()}</div>
      </div>
      // </div>
    )
  }
}